package com.ruoyi.kis.controller;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult_KIS;
import com.ruoyi.kis.Vars.Constants;
import com.ruoyi.kis.annotaion.BasicAuthCheck;
import com.ruoyi.kis.domain.ProductStoreF;
import com.ruoyi.kis.domain.SclkdFPo;
import com.ruoyi.kis.service.IKisService;
import com.ruoyi.kis.util.HttpSendWmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author: zhanglm
 * @CreateDate: 2025-02-26 14:04
 * @FullNameClass: com.ruoyi.kis.controller.KisProductInWareController
 * @Description: 生产入库、生产入库反馈，生产入库逆向反馈
 */
@RestController
@RequestMapping("/kiscrkd")
@Component("kissclkd")
@Api("kis接口")
public class KisSClkdController extends BaseController {
    @Autowired
    private IKisService kisService;

    private static final Logger LOGGER = LoggerFactory.getLogger(KisSClkdController.class);
    /**
     * 产品入库单（红）下发
     * ERP > WMS
     *
     * sql：quantity必须 > 0，否则wms不接收
     */
    @ApiOperation("产品入库单（红）下发")
    @RequestMapping("/scrk")
    public AjaxResult_KIS prodStore(){
        List<ProductStoreF> productStoreFList = kisService.queryProdStore();
        if (productStoreFList == null || productStoreFList.isEmpty() || productStoreFList.size() == 0){
            return AjaxResult_KIS.error("error","未查询到相关单据");
        }
        String s  = "";
        if (productStoreFList != null){
            s = JSONUtil.parse(productStoreFList.get(0)).toString();
            try {
//                String msg = HttpUtil.post(Constants.RED_CPLKD_URL,s);
                String msg = HttpSendWmsUtil.sendWms(Constants.RED_CPLKD_URL,s);
                LOGGER.info("产品入库单（红）下发JSON："+s);
                JSONObject entries = JSONUtil.parseObj(msg);
                String msgcode = entries.get("msgcode").toString();
                String kisFlag;
                if (msgcode.equals(Constants.ZHIKU.MSGCODE_SUCCESS)){
                    kisFlag = Constants.ZHIKU.KISFLAG_SUCCESS;
                }else {
                    kisFlag = Constants.ZHIKU.KISFLAG_FAILURE;
                }
                int countUpdate = kisService.updateKisICStockBillFlag(productStoreFList.get(0).getFInterID(),kisFlag);
                LOGGER.info("产品入库单（红）下发单据号：{}更新:{}条,更新kisFlag状态:{},下发反馈：{}",productStoreFList.get(0).getFBillNo(),countUpdate,kisFlag,msg);
            }catch (HttpException e){
                LOGGER.error("产品入库单（红）下发下发反馈失败" + e.getMessage());
                return AjaxResult_KIS.error("产品入库单（红）下发失败");
            }
        }
        return AjaxResult_KIS.success("OK",productStoreFList);
    }
    /**
     * 产品入库反馈（wms生成的时候使用这个接口）
     */
    @ApiOperation("产品入库反馈")
    @RequestMapping("/scrkfeedback")
    @BasicAuthCheck
    public AjaxResult_KIS prodStoreFeedback(@RequestBody SclkdFPo sclkdFPo){
        LOGGER.info("KisSClkdController>>>>>prodStoreFeedback产品入库反馈："+sclkdFPo);
        Map map = kisService.saveProdStore(sclkdFPo);
        LOGGER.info("KisSClkdController>>>>>prodStoreFeedback产品入库反馈："+map);
        JSON parse = JSONUtil.parse(sclkdFPo);
        String s =  parse.toString();
        if(map.get("MSGCODE").toString().equals("0")){
            return AjaxResult_KIS.success("success","");
        }else {
            return AjaxResult_KIS.error("error",map.get("MSG").toString());
        }

    }
    /**
     * 产品入库反馈
     */
    @ApiOperation("产品入库(红)反馈")
    @RequestMapping("/scrkfeedbackupdate")
    @BasicAuthCheck
    public AjaxResult_KIS prodStoreUpdateFeedback(@RequestBody @Validated SclkdFPo sclkdFPo){
        LOGGER.info("KisSClkdController>>>>>scrkfeedbackupdate产品入库(红)反馈："+sclkdFPo);
        Map map = kisService.updateProdStore(sclkdFPo);
        LOGGER.info("KisSClkdController>>>>>scrkfeedbackupdate产品入库(红)反馈："+map);
        JSON parse = JSONUtil.parse(sclkdFPo);
        String s =  parse.toString();
        if(map.get("MSGCODE").toString().equals("0")){
            return AjaxResult_KIS.success("success","更新完成");
        }else {
            return AjaxResult_KIS.error("error",map.get("MSG").toString());
        }

    }
}
